import React from 'react'
import { connect } from 'react-redux'
import menuRoute from "routes/menuRoute";
import borrowService from "containers/loan-billing/borrow-and-return.service";
import { message, Affix, Button, Popconfirm } from "antd";
import AuditApplicationDetail from 'containers/financial-management/finance-audit/audit-application-detail';
import LoanBtn from 'containers/approve/loan/loan-btn'
import {getQueryUrlParam, messages} from "share/common";
import ExpenseCheckResult from 'containers/expense-report/components/expense-check-result'
import Condition from 'components/condition'
import ButtonPrintCertificate from 'containers/expense-report/components/button-print-certificate'
import adminApproveListService from "../../setting/process-monitoring-platform/admin-approve-list.service";
const { If } = Condition;

class BottomButton extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      info: {},
      formInfo: {},
      buttonRoleSwitch:this.checkPageRole('EXPENSEAUDIT', 2) && this.checkFunctionProfiles(['er.disabled'], [[false, undefined]]) && this.checkFunctionProfiles(['finance.audit.disabled'], [[false, undefined]]), //按钮操作权限
      audit: false,
      view: false,
      approve: false,
      showApproveBottom: false, //是否显示底部审批／驳回等按钮
      confirmPay: false,
      printLoading: false,
      recallVisible: false,
      drawLoading: false,
      submitLoading: false,
      deleteLoading: false,
      urgeLoading: false,
      myBorrow: menuRoute.getRouteItem('my-borrow'),
      approving: false,
      loanTableData: [],
      checkResult: [],
      showCheckResult: false
    }
  }

  componentDidMount() {
    this.setState({
      audit: this.props.location.pathname.indexOf('loan-detail-audit') > -1,
      view: this.props.location.pathname.indexOf('loan-detail-view') > -1,
      confirmPay: this.props.location.pathname.indexOf('loan-detail-payment') > -1,
      approve: this.props.location.pathname.indexOf('approve-loan-detail') > -1,
      approving: this.props.location.query.approving
    });
    if(Object.keys(this.props.info).length > 0){
      this.setState({ info: this.props.info,formInfo: this.props.formInfo,loanTableData: this.props.loanTableData },() => {
        const { formInfo, info } = this.state;
        const { user } = this.props;
        let recallVisible = false;
        let temp = formInfo.customFormPropertyMap ? formInfo.customFormPropertyMap.formWithdrawAuthority : '0';
        if (temp === '1' || (temp === '2' && info.withdrawFlag === 'Y')) {
          recallVisible = true;
        }
        this.setState({recallVisible});
        this.setState({showApproveBottom: this.showApproveButton(info.approvalChain, info.approvalChains, user.userOID, info.status)});
      });
    }else{
      this.setState({info: {},formInfo: {},loanTableData: []});
    }
  };

  componentWillReceiveProps(nextProps){
    this.setState({
      audit: nextProps.location.pathname.indexOf('loan-detail-audit') > -1,
      view: nextProps.location.pathname.indexOf('loan-detail-view') > -1,
      confirmPay: nextProps.location.pathname.indexOf('loan-detail-payment') > -1,
      approve: nextProps.location.pathname.indexOf('approve-loan-detail') > -1,
      approving: nextProps.location.query.approving
    });
    if(Object.keys(nextProps.info).length > 0){
      const { user } = this.props;
      this.setState({ info: nextProps.info,formInfo: nextProps.formInfo, loanTableData: nextProps.loanTableData }, () => {
        const { formInfo, info } = this.state;
        let recallVisible = false;
        let temp = formInfo.customFormPropertyMap ? formInfo.customFormPropertyMap.formWithdrawAuthority : '0';
        if (temp === '1' || (temp === '2' && info.withdrawFlag === 'Y')) {
          recallVisible = true;
        }
        this.setState({recallVisible});
      });
      this.setState({showApproveBottom: this.showApproveButton(nextProps.info.approvalChain, nextProps.info.approvalChains, user.userOID, nextProps.info.status)});
    }else{
      this.setState({info: {},formInfo: {},loanTableData: []});
    }
  }

  //判断是否显示底部审批／驳回等按钮
  showApproveButton = (approvalChain, approvalChains, currentUserId, status) => {
    let showBottom = false;
    if(status !== 1002){
      return;
    }
    if(approvalChain){
      if(approvalChain.approverOID == currentUserId){
        showBottom = true;
      }
    }
    if(approvalChains){
      approvalChains.forEach((approver) => {
        if(approver.approverOID == currentUserId){
          showBottom = true;
        }else{
          if(approver.proxyApproverOIDs){
            approver.proxyApproverOIDs.forEach((proxyApprover) => {
              if(proxyApprover == currentUserId){
                showBottom = true;
              }
            })
          }
        }
      })
    }
    return showBottom;
  };

  handlePrint = () => {
    this.setState({ printLoading: true });
    borrowService.printLoanApplication(this.state.info.loanBillOID).then(res => {
      this.setState({ printLoading: false });
      window.open(res.data.link, '_blank')
    }).catch(() => {
      this.setState({ printLoading: false })
    })
  };

  //返回
  goBack = () => {
    // TODO 'request-edit'和 'request-detail'废弃了，所以直接返回，如果有问题再改
    // menuRoute.goBack(this)
    // this.context.router.push(menuRoute.getRouteItem('my-borrow'))
    this.context.router.push(this.state.myBorrow.url);
    // if(this.props.routeObj.backType && this.props.routeObj.backType === 'history') {
    //   window.history.go(-1);
    // } else {
    //   const { applicationOID, requestInfo } = this.props;
    //   if(applicationOID){
    //     this.context.router.push(menuRoute.getRouteItem(requestInfo.status === 1001 ? 'request-edit' : 'request-detail').url.replace(':formOID',requestInfo.formOID).replace(':applicationOID',applicationOID))
    //   }else{
    //     menuRoute.goBack(this)
    //     // this.context.router.push(this.state.myBorrow.url);
    //   }
    // }
  };

  handleRecall = () => {
    let params = {
      entities:[{
        entityOID: this.state.info.loanBillOID,
        entityType: 3001
      }]
    };
    this.setState({ drawLoading: true });
    borrowService.recallRequest(params).then(res => {
      this.setState({ drawLoading: false });
      if (res.data.failNum) {
        let reason = '';
        Object.keys(res.data.failReason).map(key => {
          reason = res.data.failReason[key]
        });
        message.error(`${messages('common.operate.filed')}，${reason}`)
      } else {
        message.success(messages('common.operate.success'));
        this.goBack();
      }
    }).catch(e => {
      this.setState({ drawLoading: false });
      message.error(`${messages('common.operate.filed')}，${e.response.data.message}`)
    })
  };

  handleSubmit = () => {
    const { info } = this.state;
    let data = info.customFormValues.filter(item => {
      return item.fieldName === '附件'
    });
    let value = data && data[0] && data[0].value ? data[0].value : undefined;
    if (info.formCode === 'JK001' && info.currencyAmount > 300000 && (!value || value == '[]')) {
      message.warning('单据金额超过DOA最高权限，请上传相关董事会决议或董事会审批。')
    } else {
      this.setState({submitLoading: true});
      borrowService.handleSubmit(JSON.parse(JSON.stringify(info))).then(res => {
        this.setState({submitLoading: false});
        if(Array.isArray(res.data)){
          this.setState({
            checkResult: res.data,
            showCheckResult: true
          })
        } else {
          message.success(messages('common.operate.success'));
          let url = menuRoute.getRouteItem('my-borrow').url;
          this.context.router.push(url);
          // this.goBack();
        }
      }).catch(() => {
        this.setState({submitLoading: false});
      })
    }
  };

  //删除
  handleDelete = () => {
    const { info } = this.state;
    this.setState({deleteLoading: true});
    borrowService.deleteRequest(info.loanBillOID).then(() => {
      this.setState({deleteLoading: false});
      message.success(messages('common.delete.success', {name: ''}));
      this.goBack()
    }).catch(() => {
      this.setState({deleteLoading: false});
      message.error(messages('common.operate.filed'))
    })
  };

  // 催办
  handleUrge = () => {
    const {info} = this.state;
    if (info.approvalChains && info.approvalChains.length > 0) {
      const {approverOID, entityOID, entityType} = info.approvalChains[0];
      const { applicantOID, businessCode, formOID } = info
      this.setState({
        urgeLoading: true
      }, () => {
        let params ={
          approverOID,
          entityOID,
          entityType,
          applicantOID,
          businessCode,
          formOID
        }
        adminApproveListService.postPressMessage(params)
          .then(res=>{
            if(res.data){
              message.info(messages('components.key746')/*已向审批人发出催办消息*/);
              setTimeout(() => {
                this.setState({ urgeLoading:false })
              }, 3000)
            }
          }).catch(e => {
          this.setState({ urgeLoading:false })
          message.error(`${e.response.data.message}`)
        });
      })
    }
  }

  render(){
    const { info, buttonRoleSwitch, audit, view , confirmPay, printLoading, recallVisible,
      drawLoading, submitLoading, deleteLoading, approve, approving, formInfo, showApproveBottom, checkResult,
      showCheckResult, urgeLoading } = this.state;
    const { applicationOID, routeObj } = this.props;
    return(
      <div>
        <If value={view}>
          <Affix offsetTop={0} className='bottom-bar'>
            {false && <Button type="primary" loading={printLoading} onClick={this.handlePrint}>{messages('common.print')/*打印*/}</Button>}
            <ButtonPrintCertificate businessCode={info.businessCode} appCode={'CA_PRINT_DOCUMENT'}/>
          </Affix>
        </If>
        <If value={info.directCreate && !view}>
          <Affix offsetBottom={0} className='bottom-bar'>
            <If value={applicationOID && info.status === 1001}>
              <Popconfirm title={messages('common.confirm.delete')} placement="topRight" onConfirm={this.handleDelete}>
                <Button style={{color:'#fff',backgroundColor:'#ff4d4f',borderColor:'#ff4d4f'}} loading={deleteLoading}>{messages('common.delete')}</Button>
              </Popconfirm>
            </If>
            <If value={false && !audit && !view && !confirmPay && !approve && ((info.status === 1002 && info.rejectType === 1000 && info.printButtonDisplay) || (info.status > 1002 && info.status < 1008))}>
              <Button type="primary" loading={printLoading} onClick={this.handlePrint}>{messages('common.print')/*打印*/}</Button>
            </If>
            <Button onClick={this.goBack} style={{marginLeft: '10px'}}>{messages("common.back")/*返回*/}</Button>
          </Affix>
        </If>
        <If value={!info.directCreate && !view}>
          <If value={!applicationOID}>
            {audit && (buttonRoleSwitch ?
                <AuditApplicationDetail
                  status={info.status}
                  tab={routeObj.tab}
                  entityOID={info.loanBillOID}
                  entityType={3001}
                  companyOid={info.companyOID}
                  approvalHistory={info.approvalHistorys}
                /> :
                <Affix offsetBottom={0} className='bottom-bar'>
                  <Button onClick={this.goBack}>{messages("common.back")/*返回*/}</Button>
                </Affix>
            )}
            {approve && (
              <Affix offsetTop={0} className='bottom-bar' style={{height:'auto'}}>
                <LoanBtn info={info} approving={!!approving && (showApproveBottom || info.admin)} formInfo={formInfo} backUrlKey={getQueryUrlParam('backUrlKey')}/>
              </Affix>
            )}
            {!audit && !view && !confirmPay && !approve && (
              <Affix offsetTop={0} className='bottom-bar'>
                {info.status === 1002 && info.rejectType === 1000 &&
                  <span>
                    {
                      recallVisible &&
                      <Button type="primary" loading={drawLoading}
                              onClick={this.handleRecall}>{messages('request.key95'/*撤 回*/)}</Button>
                    }
                    {
                      [1002].includes(Number(info.status || 0)) ?
                        <Button
                          disabled={urgeLoading}
                          onClick={() => this.handleUrge()}
                          type={'primary'}
                          style={{marginLeft: "10px"}}
                        >
                          催办
                        </Button> : null
                    }
                    {
                      info.printButtonDisplay && false &&
                      <Button type="primary" loading={printLoading} onClick={this.handlePrint}
                              style={{marginLeft: "10px"}}>{messages('common.print')/*打印*/}</Button>
                    }
                  </span>
                }
                {info.status === 1001 && (
                  <span>
                    <Button type="primary" onClick={this.handleSubmit} loading={submitLoading}
                            style={{marginRight: '10px'}}>{messages('common.submit')}</Button>
                    <Popconfirm title={messages('common.confirm.delete')} placement="topRight"
                                onConfirm={this.handleDelete}>
                      <Button style={{color: '#fff', backgroundColor: '#ff4d4f', borderColor: '#ff4d4f'}}
                              loading={deleteLoading}>{messages('common.delete')}</Button>
                    </Popconfirm>
                  </span>
                )}
                {/* <Button type="primary" onClick={this.handleSubmit} loading={submitLoading}
                            style={{marginRight: '10px'}}>{messages('common.submit')}</Button> */}
                {info.status > 1002 && info.status < 1008 && false &&
                <Button type="primary" loading={printLoading} onClick={this.handlePrint}>{messages('common.print')/*打印*/}</Button>}
                <Button onClick={this.goBack} style={{marginLeft:'10px'}}>{messages('common.back')}</Button>
              </Affix>
            )}
            {!audit && !view && confirmPay && !approve && (
              <Affix offsetBottom={0} className='bottom-bar'>
                <Button onClick={this.goBack}>{messages("common.back")/*返回*/}</Button>
              </Affix>
            )}
          </If>
          <If value={applicationOID}>
            <Affix offsetBottom={0} className='bottom-bar'>
              <Button onClick={this.goBack}>{messages("common.back")/*返回*/}</Button>
            </Affix>
          </If>
        </If>
        <ExpenseCheckResult
          visible={showCheckResult}
          checkResult={checkResult}
          onCancel={() => {
            this.setState({showCheckResult: false})
          }}
        />
      </div>
    )
  }
}

BottomButton.contextTypes = {
  router: React.PropTypes.object
};

BottomButton.propTypes = {
  info: React.PropTypes.object,
  routeObj: React.PropTypes.object,
  location: React.PropTypes.any,
  formInfo: React.PropTypes.object,
  applicationOID: React.PropTypes.string,
  requestInfo: React.PropTypes.object
};

BottomButton.defaultProps = {
  info: {},
  routeObj: {},
  location: {},
  applicationOID: ''
};

function mapStateToProps(state) {
  return {
    user: state.login.user
  }
}

export default connect(mapStateToProps)(BottomButton);
